using Dapper;
using Finance.Api.Read.Applications.Commands.库存盘点;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;

namespace Finance.Api.Read.Applications.CommandHands.库存盘点
{
    public class CheckQueryCommandHandlers : IRequestHandler<CheckQueryCommand, ApiResult<ApiPaging<List<CheckDto>>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<CheckQueryCommandHandlers> _logger;

        public CheckQueryCommandHandlers(IDapperDb db, ILogger<CheckQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<ApiPaging<List<CheckDto>>>> Handle(CheckQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ApiPaging<List<CheckDto>>>();
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder totalNum = new StringBuilder();

            ApiPaging<List<CheckDto>> res = new ApiPaging<List<CheckDto>>();
            var parameters = new DynamicParameters();
            try
            {
                stringBuilder.Append(@"SELECT a.Id,
                            a.Checkno,
                             a.CheckType,
                            a.CheckStatus,
                            a.CheckName,
                            a.ChenckScope,
                            a.CheckTime,
                            a.CreateName,
                            a.CreateTime,
                            a.UpdateName,
                            a.UpdateTime,
                            a.DeleteName,
                            a.DeleteTime
                    FROM `Check` a
                    WHERE 1=1
                            AND a.IsDelete=0 ");

                // 任务编号查询条件
                if (!string.IsNullOrEmpty(request.Checkno))
                {
                    stringBuilder.Append(" AND a.Checkno LIKE @Checkno ");
                    parameters.Add("Checkno", $"%{request.Checkno}%");
                }

                // 创建时间开始查询条件
                if (request.CreateTimeStart.HasValue)
                {
                    stringBuilder.Append(" AND a.CreateTime >= @CreateTimeStart ");
                    parameters.Add("CreateTimeStart", request.CreateTimeStart.Value);
                }

               

                // 盘点状态查询条件
                if (request.CheckStatus.HasValue)
                {
                    stringBuilder.Append(" AND a.CheckStatus = @CheckStatus ");
                    parameters.Add("CheckStatus", request.CheckStatus.Value);
                }

                // 构建总数查询SQL
                totalNum.Append(@"SELECT COUNT(1)
                            FROM `Check` a
                            WHERE 1=1
                                    AND a.IsDelete=0 ");

                // 为总数查询添加相同的查询条件
                if (!string.IsNullOrEmpty(request.Checkno))
                {
                    totalNum.Append(" AND a.Checkno LIKE @Checkno ");
                }

                if (request.CreateTimeStart.HasValue)
                {
                    totalNum.Append(" AND a.CreateTime >= @CreateTimeStart ");
                }

               

                if (request.CheckStatus.HasValue)
                {
                    totalNum.Append(" AND a.CheckStatus = @CheckStatus ");
                }

                // 执行总数查询
                int totalCount = await _db.QueryFirst<int>(totalNum.ToString(), parameters);

                // 添加分页和排序
                stringBuilder.Append($" ORDER BY a.Id DESC LIMIT {((request.index - 1) * request.size)}, {request.size}");

                // 执行数据查询
                var list = await _db.Query<CheckDto>(stringBuilder.ToString(), parameters);
                
                res.data = list.ToList();
                res.totalcount = totalCount;
                res.totalpcount = (int)Math.Ceiling(totalCount * 1.0 / request.size);
                result.data = res;
                result.message = "库存盘点分页查询成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("库存盘点分页查询失败: {Message}", ex.Message);
                result.message = "库存盘点分页查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 